<?php
/**
 * Created by IDEA.
 * User: dinesh
 * Date: Feb 25, 2012
 * Time: 8:00:50 PM
 */
 
class BaseRouter {
    private $catchAllRequest;
    private $controllerID;
    private $actionID;

    public function processRequest()
    {
        $this->setRequest();
        if(is_array($this->catchAllRequest) && isset($this->catchAllRequest[0]))
        {
            $route=$this->catchAllRequest[0];

        }
        else
          $route=CmbBaseConfig::getConfig('DefaultController') ;
       // echo $route;
        $this->runController($route);
    }
    public function setRequest(){
        if (!empty($_SERVER['QUERY_STRING'])){
             $this->catchAllRequest = explode('&' , $_SERVER['QUERY_STRING']);
        } 

    }

    public function runController($route=null){
        if($route==null){
            $this->controllerID =CmbBaseConfig::getConfig('DefaultController') ;
        }
        if(stripos($route,'/')===false){
            $this->controllerID =$route ;
            $this->actionID = '';

        }
        else{
            list($this->controllerID , $this->actionID) = explode('/' , $route);
        }
        $class = ucfirst($this->controllerID) . 'Controller';   // can improved this code
        $target = SERVER_ROOT . '/controllers/' . ucfirst($class) . '.php';
        if (file_exists($target))
        {
            include_once($target);
            $action = 'action'. ucfirst($this->actionID);
            if (class_exists($class))
            {
                $controller = new $class($this->controllerID);

                    if(method_exists($controller,$action)){
                       $controller->$action();
                    } else{
                        $controller->actionError();
                    }


            }
            else
            {
               die('class does not exist!');
            }
        }
        else
        {
         //  $this->urlRedirect('site/noPage');
            if(isset($_SESSION['user_id']))  {
              header("Location: index.php?site/noPage");
            exit();
            }else{
             header("Location: index.php?site/login");
            exit();
            }

        }
    }

}
